package com.du.cloud.oauth.config;

import com.du.cloud.oauth.model.User;
import com.du.cloud.oauth.model.info.UserDetail;
import com.du.cloud.oauth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Desc:
 * Author: dushuang
 * Date 2019/12/30 15:19
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private MyUserDetailsService userDetailService;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserService userService;

    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    // 定义令牌端点上的安全性约束
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 从数据库中取客户端配置
        clients.withClientDetails(clientDetails());
        // 自定义到内存中
//        clients.inMemory()
//                .withClient("test")
//                .secret("7a0f914ab4853c5d742bfc01a7a2f9bb")
//                .redirectUris("https://www.baidu.com")
//                .scopes("read","write")
//                .authorizedGrantTypes("password", "authorization_code", "refresh_token")
//                .and()
//                .withClient("browser")
//                .scopes("read")
//                .authorizedGrantTypes("implicit");
    }

    @Bean
    public ClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    }

//    @Bean
//    public WebResponseExceptionTranslator webResponseExceptionTranslator() {
//        return new DefaultWebResponseExceptionTranslator();
//    }


    // 定义授权和令牌端点以及令牌服务
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                // 刷新token的值每次不一样
                .reuseRefreshTokens(false)
                .tokenStore(tokenStore())
                .userDetailsService(userDetailService)
//                .userApprovalHandler(new DefaultUserApprovalHandler())
                .authenticationManager(authenticationManager);
//        endpoints.tokenServices(defaultTokenServices());

        // 加入自定义字段
        endpoints.tokenEnhancer((oAuth2AccessToken, oAuth2Authentication) -> {
            if (oAuth2Authentication.getUserAuthentication() != null) {
                DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oAuth2AccessToken;
                UserDetail user = (UserDetail) oAuth2Authentication.getPrincipal();
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("realName", user.getRealName());
                map.put("phone", user.getPhone());
                map.put("email",user.getEmail());
                token.setAdditionalInformation(map);
                oAuth2Authentication.setDetails(user);
            } else {
                // 客户端模式需要查询到用户
                System.out.println(oAuth2Authentication.getOAuth2Request().getClientId());
                User user = userService.getUserByClientId(oAuth2Authentication.getOAuth2Request().getClientId());
                UserDetail userDetail = new UserDetail(user, Collections.EMPTY_LIST);
                oAuth2Authentication.setDetails(userDetail);
            }
            return oAuth2AccessToken;
        });

    }

    /**
     * <p>
     *     注意，自定义TokenServices的时候
     *     需要设置@Primary，否则报错
     * </p>
     */
//    @Primary
//    @Bean
//    public DefaultTokenServices defaultTokenServices(){
//        DefaultTokenServices tokenServices = new DefaultTokenServices();
//        tokenServices.setTokenStore(tokenStore());
//        tokenServices.setSupportRefreshToken(true);
//        tokenServices.setClientDetailsService(clientDetails());
//        // token有效期自定义设置，默认12小时
//        tokenServices.setAccessTokenValiditySeconds(60 * 60 * 12);
//        // refresh_token默认30天
//        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24);
//        return tokenServices;
//    }


}
